<?php

namespace App\Service\CodeService;

use App\Service\BaseService;
use App\Service\InterfaceService\CodeBuilderInterface;

class UuidBuilderService extends BaseService implements CodeBuilderInterface
{
    public $uniqueStr = null;
    
    /**
     * 获取NonceStr
     */
    public function getCode():string
    {
        $uniqueStr = $this->getUniqueStr();
        //如果毫秒数相同，则休眠一毫秒之后
        if( $this->uniqueStr == $uniqueStr )
        {
            usleep(1000);
            $uniqueStr = $this->getUniqueStr();
        }
        
        //赋值当前skuCode
        $this->uniqueStr = $uniqueStr;
        return $uniqueStr;
    }
    
    /**
     * 获取唯一符串
     * @return string
     */
    protected function getUniqueStr()
    {
        $a4 = uniqid().rand(10,99);
        $a4 = $this->insertToStr($a4,4,'-');  //这里是后面两组的唯一值 如5770-A529AD987M
        $a4 = $a4.$this->GetRandStr(1);
        $a1 = $this->GetRandStr(8);
        $a2 = $this->GetRandStr(4);
        $a3 = $this->GetRandStr(4);
        $val = $a1.'-'.$a2.'-'.$a3.'-'.$a4;
        return strtoupper($val);
    }
    
    /**
     * 指定位置插入字符串
     * @param $str  原字符串
     * @param $i    插入位置
     * @param $substr 插入字符串
     * @return string 处理后的字符串
     */
    public function insertToStr($str, $i, $substr)
    {
        $startstr="";
        for($j=0; $j<$i; $j++){
            $startstr .= $str[$j];
        }
        //指定插入位置后的字符串
        $laststr="";
        for ($j=$i; $j<strlen($str); $j++){
            $laststr .= $str[$j];
        }
        //将插入位置前，要插入的，插入位置后三个字符串拼接起来
        $str = $startstr . $substr . $laststr;
        //返回结果
        return $str;
    }
    
    /**
     * 获得指定位数随机数
     * @param $length  指定位数
     * @return string  处理后的字符串
     */
    public function GetRandStr($length)
    {
        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
}